from flask import Flask, session, g, redirect, url_for
import config
from exts import db, mail
from models import UserModel
from blueprints.auth import bp as auth_bp
from blueprints.stu import bp as stu_bp
from blueprints.exam import bp as exam_bp
from blueprints.backend import bp as back_bp
from blueprints.tea import bp as tea_bp
from flask_migrate import Migrate

app = Flask(__name__)
# 绑定配置文件
app.config.from_object(config)

db.init_app(app)
mail.init_app(app)

"""
你可以通过以下三条终端命令将数据(包括结构)同步到数据库中
1、flask db init(只需执行一次)
2、flask db migrate
3、flask db upgrade
"""
migrate = Migrate(app, db)

app.register_blueprint(auth_bp)
app.register_blueprint(stu_bp)
app.register_blueprint(exam_bp)
app.register_blueprint(back_bp)
app.register_blueprint(tea_bp)


@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    if user_id:
        user = UserModel.query.get(user_id)
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)


@app.context_processor
def my_context_processor():
    return {"user": g.user}


@app.route('/')
def index():
    return redirect(url_for('auth.login'))


if __name__ == '__main__':
    app.run(debug=True)
    with app.app_context():
        db.create_all()
